package org.springblade.task.job.report.operation;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.utils.DateUtils;
import org.springblade.modules.operationAnalysis.entity.DailyActivityTypeReport;
import org.springblade.modules.operationAnalysis.service.IDailyActivityTypeReportService;
import org.springblade.task.base.param.BaseOrderBookParam;
import org.springblade.task.base.param.BaseShowLogParam;
import org.springblade.task.base.param.BaseUserClickLogParam;
import org.springblade.task.base.service.*;
import org.springblade.task.base.vo.*;
import org.springblade.task.job.base.BaseTaskInfoJob;
import org.springblade.task.quartz.entity.QuartzTask;
import org.springblade.task.quartz.service.IQuartzTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Title: 活动类型转换效果分析
 * @version V1.0
 */
@Component
public class DailyActivityTypeReportJob {

	private static Logger logger = LoggerFactory.getLogger(BaseTaskInfoJob.class);

	@Autowired
	private IQuartzTaskService quartzTaskService;
	@Autowired
	private IBaseShowLogService baseShowLogService;
	@Autowired
	private IBaseUserClickLogService baseUserClickLogService;
	@Autowired
	private IBaseEbookOrderService baseEbookOrderService;
	@Autowired
	private IBaseNetChapterOrderService baseNetChapterOrderService;
	@Autowired
	private IBaseAudioChapterOrderService baseAudioChapterOrderService;

	@Autowired
	private IDailyActivityTypeReportService dailyActivityTypeReportService;

	/**
	 * 1、简单任务示例（Bean模式）
	 */
	@XxlJob("dailyActivityTypeReportJob")
	public ReturnT<String> dailyActivityTypeReportJob(String param) throws Exception {
		System.out.println(DateUtils.currentDateTime() + " -- XXL-JOB, Hello World.");
		System.err.println("执行静态定时任务日期: " + DailyActivityTypeReportJob.class.getSimpleName());
		QuartzTask quartzTask = quartzTaskService.queryByTaskName(DailyActivityTypeReportJob.class.getSimpleName(), -7);
		// 今日
		String todayDate = DateUtils.crutDate();
		String taskDate = quartzTask.getTaskDate();
		while (taskDate.compareTo(todayDate) < 0) {
			// 当时间大于5点，跳出执行
//			if (DateUtils.getHour24() > 5) {
//				break;
//			}
			// 再加一个凌晨1点判断
			currMethod(taskDate);
			// 增加1天
			taskDate = DateUtils.dateAddDay(taskDate, 1);
		}
		quartzTask.setTaskDate(taskDate);
		quartzTaskService.saveQuartzTask(quartzTask);
		return ReturnT.SUCCESS;
	}

	/**
	 *
	 * @param taskDate
	 */
	public void currMethod(String taskDate) {

		String startTime = DateUtils.getDateStartTime(taskDate);
		String endTime = DateUtils.getDayEndTime(taskDate);
		BaseShowLogParam logParam = new BaseShowLogParam();
		// 曝光数
		List<BaseShowLogVO> showLogVOList = baseShowLogService.queryDailyActivityTypeShowCount(logParam);

		BaseUserClickLogParam clickLogParam = new BaseUserClickLogParam();
		clickLogParam.setStartDate(startTime);
		clickLogParam.setEndDate(endTime);
		// 点击数、点击人数
		List<BaseUserClickLogVO> clickLogVOList = baseUserClickLogService.queryDailyActivityTypeList(clickLogParam);

		BaseOrderBookParam orderParam = new BaseOrderBookParam();
		orderParam.setStartDate(startTime);
		orderParam.setEndDate(endTime);
		// 电子书订单
		Map<String, BaseEbookOrderVO> ebookOrderVOMap = new HashMap<>();
		List<BaseEbookOrderVO> ebookOrderVOList = baseEbookOrderService.queryDailyOrderList(orderParam);
		for (BaseEbookOrderVO ebookOrderVO : ebookOrderVOList) {
			ebookOrderVOMap.put(String.valueOf(ebookOrderVO.getOrderId()), ebookOrderVO);
		}
		// 网文订单
		List<BaseNetChapterOrderVO> netChapterOrderVOList = baseNetChapterOrderService.queryDailyOrderList(orderParam);
		Map<String, BaseNetChapterOrderVO> netChapterOrderVOMap = new HashMap<>();
		for (BaseNetChapterOrderVO netChapterOrderVO : netChapterOrderVOList) {
			netChapterOrderVOMap.put(String.valueOf(netChapterOrderVO.getOrderId()), netChapterOrderVO);
		}
		// 有声订单
		List<BaseAudioChapterOrderVO> audioChapterOrderVOList = baseAudioChapterOrderService.queryDailyOrderList(orderParam);
		Map<String, BaseAudioChapterOrderVO> audioChapterOrderVOMap = new HashMap<>();
		for (BaseAudioChapterOrderVO audioChapterOrderVO : audioChapterOrderVOList) {
			audioChapterOrderVOMap.put(String.valueOf(audioChapterOrderVO.getOrderId()), audioChapterOrderVO);
		}

		Map<String, Integer> dailyActivityTypeClickMap = new HashMap<>();
		Map<String, Set<String>> dailyActivityTypeClickUserMap = new HashMap<>();
		Map<String, Long> dailyActivityTypeSaleAmountMap = new HashMap<>();
		Map<String, Integer> dailyActivityTypeSaleNumMap = new HashMap<>();
		for (BaseUserClickLogVO clickLogVO : clickLogVOList) {
			String activityTypeKey = clickLogVO.getModType() + "-" + clickLogVO.getOs() + "-" + clickLogVO.getClient();
			// 活动类型点击数
			int num = dailyActivityTypeClickMap.get(activityTypeKey) == null ? 0 : dailyActivityTypeClickMap.get(activityTypeKey);
			dailyActivityTypeClickMap.put(activityTypeKey, num + 1);
			// 活动类型点击人
			Set<String> pinSet = dailyActivityTypeClickUserMap.get(activityTypeKey);
			if (null == pinSet) {
				pinSet = new HashSet<>();
			}
			pinSet.add(clickLogVO.getPin());
			dailyActivityTypeClickUserMap.put(activityTypeKey, pinSet);

			// 活动类型点击购买数据
			if (clickLogVO.getClickType() == 60) {
				Integer saleNum = dailyActivityTypeSaleNumMap.get(activityTypeKey);
				Long amount = dailyActivityTypeSaleAmountMap.get(activityTypeKey);
				BaseEbookOrderVO ebookOrderVO = ebookOrderVOMap.get(clickLogVO.getResId());
				if (null != ebookOrderVO) {
					amount = amount + ebookOrderVO.getPayAmount();
				}
				BaseNetChapterOrderVO netChapterOrderVO = netChapterOrderVOMap.get(clickLogVO.getResId());
				if (null != netChapterOrderVO) {
					amount = amount + netChapterOrderVO.getOnlineAmount();
				}
				BaseAudioChapterOrderVO audioChapterOrderVO = audioChapterOrderVOMap.get(clickLogVO.getResId());
				if (null != audioChapterOrderVO) {
					amount = amount + audioChapterOrderVO.getOnlineAmount();
				}
				saleNum = saleNum + 1;
				dailyActivityTypeSaleNumMap.put(activityTypeKey, saleNum);
				dailyActivityTypeSaleAmountMap.put(activityTypeKey, amount);
			}
		}

		List<DailyActivityTypeReport> activityTypeReportList = new ArrayList<>();
		DailyActivityTypeReport activityTypeReport = null;
		for (BaseShowLogVO showLogVO : showLogVOList) {
			String activityType = "";
			if (showLogVO.getModType() == 1) {
				activityType = "banner";
			} else if (showLogVO.getModType() == 2) {
				activityType = "五个圈";
			} else if (showLogVO.getModType() == 4) {
				activityType = "四宫格";
			} else if (showLogVO.getModType() == 5) {
				activityType = "合集";
			} else if (showLogVO.getModType() == 6) {
				activityType = "列表";
			} else if (showLogVO.getModType() == 7) { // 中部banner
				activityType = "中通";
			} else if (showLogVO.getModType() == 10) {
				activityType = "开屏广告";
			} else if (showLogVO.getModType() == 11) {
				activityType = "运营弹窗";
			}

			String key = showLogVO.getModType() + "-" + showLogVO.getOs() + "-" + showLogVO.getClient();
			activityTypeReport = new DailyActivityTypeReport();
			activityTypeReport.setDate(taskDate);
			activityTypeReport.setActivityType(activityType);
			activityTypeReport.setOs(showLogVO.getOs());
			activityTypeReport.setClient(showLogVO.getClient());
			activityTypeReport.setExposureNum(showLogVO.getNum()); //曝光数

			activityTypeReport.setSalesAmount(dailyActivityTypeSaleAmountMap.get(key));
			activityTypeReport.setSalesNum(dailyActivityTypeSaleNumMap.get(key));

			//点击进入次数
			int clickToEnterNum = dailyActivityTypeClickMap.get(key) == null ? 0 : dailyActivityTypeClickMap.get(key);
			activityTypeReport.setClickToEnterNum(clickToEnterNum);

			Set<String> pinSet = dailyActivityTypeClickUserMap.get(key);
			if (null == pinSet) {
				activityTypeReport.setBuyUserNum(0);
			} else {
				activityTypeReport.setBuyUserNum(pinSet.size());
			}
			activityTypeReportList.add(activityTypeReport);
		}

		dailyActivityTypeReportService.saveBatch(activityTypeReportList);

	}


	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
